package com.wthink.newMain.settings.config.inner.calendar

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wthink.hzgj.BusApplication
import com.wthink.hzgj.data.Result
import com.wthink.hzgj.service.DevService
import com.wthink.hzgj.util.toast
import com.wthink.newMain.data.AutoTimingData
import kotlinx.coroutines.*
import java.math.BigDecimal

class CalendarSettingsViewmodel : ViewModel() {

    var mix = 0L
    val autoTimingData = MutableLiveData<AutoTimingData>()

    fun getData(success: (autoTimingData: AutoTimingData) -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            val ret = DevService.getAutoTimeConfig()
            if (ret is Result.Success) {
                val data = ret.data
                autoTimingData.postValue(data)
                success(data)
            }
        }
    }

    fun getTime(success: (notime: BigDecimal) -> Unit){
        viewModelScope.launch(Dispatchers.IO) {
            val ret = DevService.getTime()
            if (ret is Result.Success) {
                val data = ret.data * 1000
                mix = data - System.currentTimeMillis() + 1000 * 60 * 60 * 8
                val nowTime: BigDecimal =
                    BigDecimal(mix).add(BigDecimal(System.currentTimeMillis()))
                success(nowTime)
            }
        }
    }

    fun config(gps: String, ntp: String, host: String, server: String) {
        viewModelScope.launch(Dispatchers.IO) {
            val ret = DevService.setAutoTimeConfig(gps, ntp, host, server)
            if (ret is Result.Success) {
                withContext(Dispatchers.Main) {
                    toast(BusApplication.busContext, "配置成功")
                }
            }
        }
    }

    fun setTime(time:String) {
        viewModelScope.launch(Dispatchers.IO) {
            val ret = DevService.setTimeConfig(time)
            if (ret is Result.Success) {
                withContext(Dispatchers.Main) {
                    toast(BusApplication.busContext, "设置成功")
                }
            }
        }
    }
}